package com.ruoyi.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.AliYunOss.AliOssUtil;
import com.ruoyi.AliYunOss.AliYunOssHandler;
import com.ruoyi.H5Send.demo.SmsSendDemo;
import com.ruoyi.agent.domain.SysAgent;
import com.ruoyi.agent.mapper.SysAgentMapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.order.Utils.OrderUtils;
import com.ruoyi.order.domain.*;
import com.ruoyi.order.mapper.SysOrderOneMapper;
import com.ruoyi.order.service.ISysOrderOneService;
import com.ruoyi.packages.domain.SysPackage;
import com.ruoyi.packages.mapper.SysPackageMapper;
import com.ruoyi.report.domain.SysReport;
import com.ruoyi.report.domain.SysReportUpDTO;
import com.ruoyi.report.mapper.SysReportMapper;
import com.ruoyi.report.service.ISysReportService;
import com.ruoyi.store.domain.SysStore;
import com.ruoyi.store.mapper.SysStoreMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysDeptService;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * 背调订单Controller
 *
 * @author ruoyi
 * @date 2024-06-24
 */
@RestController
@RequestMapping("/order/order")
public class SysOrderOneController extends BaseController
{
    @Autowired
    private ISysOrderOneService sysOrderOneService;

    @Autowired
    private SysAgentMapper agentMapper;

    @Autowired
    private SysPackageMapper packageMapper;

    @Autowired
    private AliYunOssHandler aliYunOssHandler;


    @Autowired
    private SysOrderOneMapper orderOneMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SysReportMapper reportMapper;

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysStoreMapper sysStoreMapper;


    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 查询背调订单列表
     */
    @PreAuthorize("@ss.hasPermi('order:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysOrderOne sysOrderOne,
                              @RequestParam(name = "params[beginCreateTime]", required = false) Date beginCreateTime,
                              @RequestParam(name = "params[endCreateTime]", required = false) Date endCreateTime)
    {
        //判断应该返回哪些订单，如果为商户，则只返回自己dept下的背调订单，如果为代理商，则返回自己下所有的dept

        Long deptId = SecurityUtils.getDeptId();
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        String type = sysDept.getType();

        if (beginCreateTime!=null) {
            sysOrderOne.setBeginCreateTime(beginCreateTime);
        }

        if (endCreateTime!=null) {
            sysOrderOne.setEndCreateTime(endCreateTime);
        }

        if (sysOrderOne.getPackageType()!=null) {
            //封装套餐ids
            List<Long> longs = packageMapper.selectSysPackageByOnline(sysOrderOne.getPackageType());
            sysOrderOne.setPackageList(longs);

        }


        List<SysOrderOne> list = new ArrayList<>();
//        startPage();
        List<SysOrderOne> listToRemove=new ArrayList<>();
        if (type.equals("2")) {
            //说明是商户查
            //sysOrderOne.setDeptId(deptId);
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByDeptId(deptId);
            if (CollectionUtils.isEmpty(sysStores)) {
                throw new ServiceException("当前用户异常");
            }

            sysOrderOne.setStoreId(sysStores.get(0).getId());

            startPage();
            list = sysOrderOneService.selectSysOrderOneList(sysOrderOne);


        }
        else if (type.equals("1")) {
            //说明是代理商查
            List<SysAgent> agents = agentMapper.selectSysAgentByDeptId(deptId);
            if (CollectionUtils.isEmpty(agents)) {
                throw new ServiceException("代理商信息异常");
            }
            SysAgent sysAgent = agents.get(0);
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByAgentId(sysAgent.getId());

            if (CollectionUtils.isEmpty(sysStores)) {
                return getDataTable(sysStores);
            }

            List<Long> storeDeptIds = sysStores.stream().map(SysStore::getDeptId).collect(Collectors.toList());

            sysOrderOne.setDeptIds(storeDeptIds);

            startPage();
           list = sysOrderOneService.selectSysOrderOneList(sysOrderOne);


        }
        else if (type.equals("0")) {
            //说明是管理员
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByAgentId(0l);

            if (CollectionUtils.isEmpty(sysStores)) {
                return getDataTable(sysStores);
            }

            List<Long> storeDeptIds = sysStores.stream().map(SysStore::getDeptId).collect(Collectors.toList());

            sysOrderOne.setDeptIds(storeDeptIds);


            startPage();
            list = sysOrderOneService.selectSysOrderOneList(sysOrderOne);

        }



        //封装代理商名称
        if (CollectionUtils.isEmpty(list)) {
            return getDataTable(list);
        }
        List<Long> agentIds = list.stream().map(SysOrderOne::getAgentId).collect(Collectors.toList());
        List<SysAgent> agents = agentMapper.selectSysAgentByIds(agentIds);
        Map<Long, String> agentMap = agents.stream().collect(Collectors.toMap(SysAgent::getId, c -> c.getName()));
        //封装套餐类型
        Set<Long> packageIds = list.stream().map(SysOrderOne::getSetmealId).collect(Collectors.toSet());
        ArrayList<Long> longs = new ArrayList<>(packageIds);
        List<SysPackage> packages = packageMapper.selectSysPackageByIds(longs);
        Map<Long, String> packageLineMap = packages.stream().collect(Collectors.toMap(SysPackage::getId, c -> c.getLineStatus()));
        for (SysOrderOne orderOne : list) {
            orderOne.setPackageType(packageLineMap.get(orderOne.getSetmealId()));
            orderOne.setIdNumber(OrderUtils.maskIDCard(orderOne.getIdNumber()));
            orderOne.setPhone(OrderUtils.maskPhoneNumber(orderOne.getPhone()));
        }



        return getDataTable(list);
    }

    /**
     * 导出背调订单列表
     */
    @PreAuthorize("@ss.hasPermi('order:order:export')")
    @Log(title = "背调订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysOrderOne sysOrderOne,
                       @RequestParam(name = "params[beginCreateTime]", required = false) Date beginCreateTime,
                       @RequestParam(name = "params[endCreateTime]", required = false) Date endCreateTime)
    {
//判断应该返回哪些订单，如果为商户，则只返回自己dept下的背调订单，如果为代理商，则返回自己下所有的dept

        Long deptId = SecurityUtils.getDeptId();
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        String type = sysDept.getType();

        if (beginCreateTime!=null) {
            sysOrderOne.setBeginCreateTime(beginCreateTime);
        }

        if (endCreateTime!=null) {
            sysOrderOne.setEndCreateTime(endCreateTime);
        }

        if (sysOrderOne.getPackageType()!=null) {
            //封装套餐ids
            List<Long> longs = packageMapper.selectSysPackageByOnline(sysOrderOne.getPackageType());
            sysOrderOne.setPackageList(longs);

        }


        List<SysOrderOne> list = new ArrayList<>();
//        startPage();
        List<SysOrderOne> listToRemove=new ArrayList<>();
        if (type.equals("2")) {
            //说明是商户查
            //sysOrderOne.setDeptId(deptId);
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByDeptId(deptId);
            if (CollectionUtils.isEmpty(sysStores)) {
                throw new ServiceException("当前用户异常");
            }

            sysOrderOne.setStoreId(sysStores.get(0).getId());

            startPage();
            list = sysOrderOneService.selectSysOrderOneList(sysOrderOne);


        }
        else if (type.equals("1")) {
            //说明是代理商查
            List<SysAgent> agents = agentMapper.selectSysAgentByDeptId(deptId);
            if (CollectionUtils.isEmpty(agents)) {
                throw new ServiceException("代理商信息异常");
            }
            SysAgent sysAgent = agents.get(0);
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByAgentId(sysAgent.getId());

            if (CollectionUtils.isEmpty(sysStores)) {
                throw new ServiceException("数据为空");
            }

            List<Long> storeDeptIds = sysStores.stream().map(SysStore::getDeptId).collect(Collectors.toList());

            sysOrderOne.setDeptIds(storeDeptIds);

            startPage();
            list = sysOrderOneService.selectSysOrderOneList(sysOrderOne);


        }
        else if (type.equals("0")) {
            //说明是管理员
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByAgentId(0l);

            if (CollectionUtils.isEmpty(sysStores)) {
                throw new ServiceException("数据为空");
            }

            List<Long> storeDeptIds = sysStores.stream().map(SysStore::getDeptId).collect(Collectors.toList());

            sysOrderOne.setDeptIds(storeDeptIds);


            startPage();
            list = sysOrderOneService.selectSysOrderOneList(sysOrderOne);

        }



        //封装代理商名称
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("数据为空");
        }
        List<Long> agentIds = list.stream().map(SysOrderOne::getAgentId).collect(Collectors.toList());
        List<SysAgent> agents = agentMapper.selectSysAgentByIds(agentIds);
        Map<Long, String> agentMap = agents.stream().collect(Collectors.toMap(SysAgent::getId, c -> c.getName()));
        //封装套餐类型
        Set<Long> packageIds = list.stream().map(SysOrderOne::getSetmealId).collect(Collectors.toSet());
        ArrayList<Long> longs = new ArrayList<>(packageIds);
        List<SysPackage> packages = packageMapper.selectSysPackageByIds(longs);
        Map<Long, String> packageLineMap = packages.stream().collect(Collectors.toMap(SysPackage::getId, c -> c.getLineStatus()));
        for (SysOrderOne orderOne : list) {
            orderOne.setUserName(orderOne.getCreateBy());
            orderOne.setPackageType(packageLineMap.get(orderOne.getSetmealId()));
            orderOne.setIdNumber(OrderUtils.maskIDCard(orderOne.getIdNumber()));
            orderOne.setPhone(OrderUtils.maskPhoneNumber(orderOne.getPhone()));
        }

        ExcelUtil<SysOrderOne> util = new ExcelUtil<SysOrderOne>(SysOrderOne.class);
        util.exportExcel(response, list, "背调订单数据");
    }

    /**
     * 获取背调订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('order:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysOrderOneService.selectSysOrderOneById(id));
    }

    /**
     * 新增背调订单
     */
    @PreAuthorize("@ss.hasPermi('order:order:add')")
    @Log(title = "背调订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysOrderOne sysOrderOne)
    {
        return toAjax(sysOrderOneService.insertSysOrderOne(sysOrderOne));
    }

    /**
     * 修改背调订单
     */
    @PreAuthorize("@ss.hasPermi('order:order:edit')")
    @Log(title = "背调订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysOrderOne sysOrderOne)
    {
        return toAjax(sysOrderOneService.updateSysOrderOne(sysOrderOne));
    }

    /**
     * 删除背调订单
     */
    @PreAuthorize("@ss.hasPermi('order:order:remove')")
    @Log(title = "背调订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysOrderOneService.deleteSysOrderOneByIds(ids));
    }




    @PostMapping("/submit")
    public AjaxResult submitOrder(@RequestBody OrderDTO orderDTO) {

        OrderOneVO orderOneVO=null;
        Integer type = orderDTO.getType();
        if (type==0) {
            //说明是单人背调,生产订单信息后返回封装给前端
          orderOneVO= sysOrderOneService.submitOneOrder(orderDTO);
        }
        else if(type ==1) {
            //批量背调
            orderOneVO= sysOrderOneService.submitMoreOrder(orderDTO);
        }

        else {
            throw new ServiceException("背调类型错误");
        }


        return success(orderOneVO);
    }
    @PostMapping("/payOrder")
     public AjaxResult payOrder(@RequestBody OrderOneVO orderOneVO) {

        sysOrderOneService.payOrders(orderOneVO);

        return success();


    }

    //授权
    @Anonymous
    @PostMapping("/empower")
    public AjaxResult empower(Long orderId, String msg, HttpServletRequest request,HttpServletResponse response) {
        sysOrderOneService.empowerUser(orderId,msg,request,response);
        return success("授权成功");
    }


    //批量模板的下载
    @Anonymous
    @GetMapping("/getTemplate")
    public ResponseEntity getTemplate(HttpServletResponse servletResponse) throws IOException {
       return aliYunOssHandler.getFileStream("批量订单上传模板.xlsx", servletResponse);



    }


    //读取批量信息返回
    @Anonymous
    @PostMapping("/getUserInfos")
    public AjaxResult getUserInfos(@RequestParam("file") MultipartFile file) throws IOException {



        List<UserInfoDTO> userInfos= new ArrayList<>();
        InputStream inputStream = file.getInputStream();
        XSSFWorkbook xssfSheets = new XSSFWorkbook(inputStream);

        XSSFSheet sheetAt = xssfSheets.getSheetAt(0);
        DataFormatter formatter = new DataFormatter();

        int a = 1;
        List<String> msg = new CopyOnWriteArrayList<>();
        while(true) {
            XSSFRow row = sheetAt.getRow(a);

            if(row!=null) {
                //获取到该行的数据数量
                int physicalNumberOfCells = row.getPhysicalNumberOfCells();
                Map<Integer,String> userInfo = new HashMap<>();
                for (int i =0;i<physicalNumberOfCells;i++) {
                    userInfo.put(i,formatter.formatCellValue(row.getCell(i)));

                }
                UserInfoDTO userInfoDTO = new UserInfoDTO();
                if (userInfo.get(0)!=null){

                    userInfoDTO.setUserName(userInfo.get(0));
                }
                if (userInfo.get(1)!=null) {
                    //校验手机号
                    boolean validMobileNumber = OrderUtils.isValidMobileNumber(userInfo.get(1));

                    if (!validMobileNumber) {
                        msg.add("第"+(a+1)+"行第"+(2)+"列,手机号:"+userInfo.get(1)+",格式错误");
                    }
                    userInfoDTO.setPhone(userInfo.get(1));
                }
                if (userInfo.get(2)!=null) {
                    //校验身份证号
                    if(!OrderUtils.isValidIDCard18(userInfo.get(2))) {
                        msg.add("第"+(a+1)+"行第"+(3)+"列,身份证:"+userInfo.get(2)+",格式错误");
                    }
                    userInfoDTO.setCard(userInfo.get(2));
                }
                if (userInfo.get(3)!=null) {
                    //校验毕业证书编号
                    if(!OrderUtils.isValidDiplomaNumber(userInfo.get(3))) {
                        msg.add("第"+(a+1)+"行第"+(4)+"列,毕业证书编号:"+userInfo.get(3)+",格式错误");

                    }
                    userInfoDTO.setGraduateCerNo(userInfo.get(3));
                }
                if (userInfo.get(4)!=null) {
                    userInfoDTO.setDegreeCerNo(userInfo.get(4));
                }
                userInfos.add(userInfoDTO);


            } else {
                break;
            }
           a++;
        }

        inputStream.close();

        if(msg.size()>0) {
            //说明有错误信息
            return new AjaxResult(HttpStatus.ERROR,"请检查 被调人 信息填写情况",msg);
        }

        return success(userInfos);
    }


    @Anonymous
    @PostMapping("/getOrderBit")
    public AjaxResult getOrderBit(Long orderId) {
        SysOrderOne sysOrderOne = orderOneMapper.selectSysOrderOneById(orderId);
        if (sysOrderOne==null) {
            throw new ServiceException("订单不存在");
        }
        SysOrderOne sysOrderOne1 = new SysOrderOne();
        sysOrderOne1.setId(sysOrderOne.getId());
        sysOrderOne1.setCdName(sysOrderOne.getCdName());
        String phone = sysOrderOne.getPhone();
        sysOrderOne1.setPhone(OrderUtils.maskPhoneNumber(sysOrderOne.getPhone()));
        sysOrderOne1.setIdNumber(OrderUtils.maskIDCard(sysOrderOne.getIdNumber()));

//        sysOrderOne1.setPhone();
//        sysOrderOne1.setIdNumber();
        return success(sysOrderOne1);
    }



    @Anonymous
    @PostMapping("/sendYZM")
    public AjaxResult sendYZM(Long orderId) {

        //根据orderId查手机号

        SysOrderOne sysOrderOne = orderOneMapper.selectSysOrderOneById(orderId);
        if (sysOrderOne==null) {
            throw new ServiceException("订单不存在");
        }

        Long payStatus = sysOrderOne.getPayStatus();
        if (payStatus.equals(0l)) {
            //说明未支付
            throw new ServiceException("订单未支付,请支付后再进行授权");
        }

        Long orderStatus = sysOrderOne.getOrderStatus();

        if (!orderStatus.equals(1l)) {
            //订单不处于待授权状态
            throw new ServiceException("订单状态错误，不可授权");
        }

        //同一个订单无法多次发送短信,短信发送成功后会对该订单id记录
        String oneMinuteKey = "order_empower_isSend_"+orderId;
        Object o = redisTemplate.opsForValue().get(oneMinuteKey);
        if (!Objects.isNull(o)) {
            throw new ServiceException("无法重复发送，请稍后再试");
        }

        String phone = sysOrderOne.getPhone();

        if(!OrderUtils.isValidMobileNumber(phone)) {
            throw new ServiceException("订单手机号错误");
        }


        //通过mq发送
        String orderString = JSONObject.toJSONString(sysOrderOne);
        rabbitTemplate.convertAndSend("sendYZM",orderString);
//        String yzm;
//        try {
//            yzm= SmsSendDemo.sendYZM(orderId, phone);
//        } catch (UnsupportedEncodingException e) {
//            throw new ServiceException("验证码发送失败");
//        }
//
//        redisTemplate.opsForValue().set(oneMinuteKey,1,1,TimeUnit.MINUTES);
//
//        //将验证码保存到redis中
//        String key = "order_empower_"+orderId;
//
//        redisTemplate.opsForValue().set(key,yzm,5, TimeUnit.MINUTES);


        return AjaxResult.success("验证码发送成功，有效期五分钟");



    }

    //上传报告给单个订单
    @PostMapping("/uploadReport")
    public AjaxResult uploadReport(@RequestBody SysReportUpDTO reportUpDTO) {


        //向订单表插入数据
        SysReport sysReport = new SysReport();
        sysReport.setOrderId(reportUpDTO.getOrderId()).setStatus(1).setResult(reportUpDTO.getResult()).setCreateBy(SecurityUtils.getUsername()).setCreateTime(LocalDateTime.now()).setUserId(SecurityUtils.getUserId()).setDeptId(SecurityUtils.getDeptId()).setUrl(reportUpDTO.getFileUrl());

        reportMapper.insertSysReport(sysReport);




        return success("上传成功");


    }


    //下载单个订单报告：
    @PostMapping("/downloadReport")
    public AjaxResult downloadReport(@RequestParam("orderId") Long orderId,HttpServletResponse httpServletResponse) {

        //首先判断当前订单是否存在，订单状态是否为已经出报告
        SysOrderOne sysOrderOne = orderOneMapper.selectSysOrderOneById(orderId);
        if (sysOrderOne==null) {
            throw new ServiceException("订单不存在");
        }

        Long orderStatus = sysOrderOne.getOrderStatus();
        if (!orderStatus.equals(3l)) {
            //说明订单还未出报告
            throw new ServiceException("订单报告未生成，请稍等");
        }


        //查询数据库对应的url
        List<SysReport> list =reportMapper.selectListByOrderId(orderId);

        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("当前订单并无报告");
        }
        List<String> collect = list.stream().map(SysReport::getUrl).collect(Collectors.toList());

        if (collect.size()>0) {
            aliOssUtil.createZipAndSend(httpServletResponse, collect, sysOrderOne);
            return success("下载中");
        }





        return error("下载失败");




    }

    /**
     *
     * 批量导出报告pdf
     * @param httpServletResponse
     * @return
     */
    @PostMapping("/downloadBatchReport")
    public AjaxResult downloadReport(HttpServletResponse httpServletResponse,SysOrderOne orderOne,
                                     @RequestParam(name = "params[beginCreateTime]", required = false) Date beginCreateTime,
                                     @RequestParam(name = "params[endCreateTime]", required = false) Date endCreateTime) {
        //数据隔离处理
        //判断应该返回哪些订单，如果为商户，则只返回自己dept下的背调订单，如果为代理商，则返回自己下所有的dept

        Long deptId = SecurityUtils.getDeptId();
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        String types = sysDept.getType();
        List<SysOrderOne> list=null;

        if (beginCreateTime!=null) {
            orderOne.setBeginCreateTime(beginCreateTime);
        }
        if (endCreateTime!=null) {
            orderOne.setEndCreateTime(endCreateTime);
        }



        //封装状态
        Long orderStatus = orderOne.getOrderStatus();
        if (orderStatus==null) {
            List<Long> statusList = new ArrayList<>();
            statusList.add(3l);
            statusList.add(4l);
            statusList.add(5l);
            orderOne.setOrderStatus(null);
            orderOne.setStatusList(statusList);
        }



        //封装套餐状态
        //套餐信息封装
        if (orderOne.getPackageType()!=null) {
            List<Long> packageIdss =packageMapper.selectSysPackageByOnline(orderOne.getPackageType());
            orderOne.setPackageList(packageIdss);
        }


        if (types.equals("2")) {
            //说明是商户查
            orderOne.setDeptId(deptId);


            startPage();
            list = orderOneMapper.selectSysOrderOneList(orderOne);
        }
        else if (types.equals("1")) {
            //说明是代理商查
            List<SysAgent> agents = agentMapper.selectSysAgentByDeptId(deptId);
            if (CollectionUtils.isEmpty(agents)) {
                throw new ServiceException("代理商信息异常");
            }
            SysAgent sysAgent = agents.get(0);
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByAgentId(sysAgent.getId());

            if (CollectionUtils.isEmpty(sysStores)) {
                throw new ServiceException("无商铺信息");
            }

            List<Long> storeDeptIds = sysStores.stream().map(SysStore::getDeptId).collect(Collectors.toList());

            orderOne.setDeptIds(storeDeptIds);

            startPage();
            list = orderOneMapper.selectSysOrderOneList(orderOne);

        }
        else if (types.equals("0")) {
            //说明是管理员
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByAgentId(0l);

            if (CollectionUtils.isEmpty(sysStores)) {
               throw new ServiceException("无店铺信息");
            }

            List<Long> storeDeptIds = sysStores.stream().map(SysStore::getDeptId).collect(Collectors.toList());

            orderOne.setDeptIds(storeDeptIds);

            startPage();
            list = orderOneMapper.selectSysOrderOneList(orderOne);

        }



        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("无报告数据");
        }
        List<Long> OrderIds = list.stream().map(SysOrderOne::getId).collect(Collectors.toList());

        //根据orderIds查询对应的报告信息，如果有，有几个
        List<SysOrderOne> orderOnes = orderOneMapper.selectSysOrderOneByIds(OrderIds);
        Map<Long, SysOrderOne> orderMap = orderOnes.stream().collect(Collectors.toMap(SysOrderOne::getId, c -> c));

        List<SysReport> reports =reportMapper.selectSysReportByOrderIds(OrderIds);

        Map<Long,List<String>> reportMap = new HashMap<>();
        for (SysReport report : reports) {
            if(!reportMap.containsKey(report.getOrderId())) {
                List<String> urlList = new ArrayList<>();
                reportMap.put(report.getOrderId(),urlList);

            }
            if (report.getUrl()!=null) {
                reportMap.get(report.getOrderId()).add(report.getUrl());
            }

        }

        if (CollectionUtils.isEmpty(reports)) {
            throw new ServiceException("无pdf报告信息");
        }
        aliOssUtil.createZipAndSendMore(httpServletResponse,reportMap,orderMap);


        return success("下载中");

    }




        //上传图片
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file,HttpServletResponse response) {
        String fileExtension = OrderUtils.getFileExtension(file);
        UUID uuid = UUID.randomUUID();
        String upload="";
        try {
            FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
            upload = aliOssUtil.upload(fileInputStream, uuid + "." + fileExtension);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return AjaxResult.success(new StringBuilder(upload));
    }




    //获取订单候选人信息
    @PostMapping("/getUserInfo/{orderId}")
    public AjaxResult getUserInfo(@PathVariable("orderId") Long orderId) {

       return sysOrderOneService.getUserInfo(orderId);


    }


    //重新发送授权短信
    @PostMapping("/sendAgain")
    public AjaxResult sendAgain(Long orderId) {

       return sysOrderOneService.sendAgain(orderId);
    }


    //获取订单状态的接口
    @PostMapping("/getOrderStatus")
    public AjaxResult getOrderStatus(Long orderId) {

        //判断当前订单是否存在
        SysOrderOne orderOne = orderOneMapper.selectSysOrderOneById(orderId);

        if (orderOne==null) {
            throw new ServiceException("订单不存在");
        }

        SysOrderStatusVO sysOrderStatusVO = new SysOrderStatusVO(orderOne.getId(), orderOne.getOrderStatus(), orderOne.getCreateTime());

        return AjaxResult.success(sysOrderStatusVO);


    }


    //调查结果的接口
    @PostMapping("/listOrderReports")
    public AjaxResult listOrderReports(@RequestParam("orderId") Long orderId,@RequestParam("type") Long type) {

        startPage();
        List<SysOrderSurveyVO> sysOrderSurveyVOS = sysOrderOneService.listOrderReports(orderId,type);


        return success(sysOrderSurveyVOS);


    }


    //查看报告
    @Anonymous
    @PostMapping("/lookReport/{orderId}")
    public AjaxResult lookReport(@PathVariable("orderId") Long orderId) {
        //通过拼接：
        SysOrderOne orderOne = orderOneMapper.selectSysOrderOneById(orderId);
        if (orderOne==null) {
            throw new ServiceException("订单不存在");
        }

        if (!orderOne.getOrderStatus().equals(3l)) {
            throw new ServiceException("订单未生成报告，请稍后重试");
        }

        String reportUrl = orderOne.getReportUrl();

        String url ="";
        if (reportUrl==null || reportUrl.equals("")) {
            //搜索report表
            List<SysReport> reports = reportMapper.selectListByOrderId(orderId);

            if(CollectionUtils.isEmpty(reports)) {
                throw new ServiceException("报告不存在");
            }

            url= reports.get(0).getUrl();


        }else {
            url = reportUrl;
        }

        //根据url获取到对应的输入流,下载到本地文件夹之前删除所有的文件,将文件路径返回前端

        //todo 730
        String pathUrl ="D:/docHtml/";

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String format = dateFormat.format(new Date());
       String fileName =orderOne.getNumber() + format + orderOne.getCdName() + ".pdf";
        String s = aliOssUtil.downloadFile(url, pathUrl + fileName);

        return success(new StringBuilder(fileName));

    }


}
